package com.cwx.service;

import com.cwx.dao.CommentRepository;
import com.cwx.pojo.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cwxstart
 * @create 2022-06-18 22:39
 */
@Service
public class CommentServiceImpl implements CommentService{

    @Autowired
    private CommentRepository commentRepository;


    @Transactional
    @Override
    //根据博客id查找评论  一个博客
    public List<Comment> listCommentByBlogId(Long blogId) {
        //按照创建时间来查询评论
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        List<Comment> byBlogId = commentRepository.findByBlogIdAndParentCommentNull(blogId, sort);
        return eachComment(byBlogId);
    }

    @Transactional
    @Override
    //保存一个博客
    public Comment saveComment(Comment comment) {
        long id = comment.getParentComment().getId();
        if (id != -1){      //默认前端的就是-1   如果就是-1 的话就说明他没有回复
            comment.setParentComment(commentRepository.findById(id).orElse(null));
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }


    /*循环每个顶级的评论节点*/
    private List<Comment> eachComment(List<Comment> comments) {

        ArrayList<Comment> commentsView = new ArrayList<>();
        for (Comment comment : comments){
            Comment c = new Comment();
            //前面的赋值给后面的  ，防止改变影响了数据库里面的值
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
//        合并评论的各层子代到第一级子代集合中
        combineChildren(commentsView);
        return commentsView;

    }

    /*root跟节点，blog不为空的对象集合*/
    private void combineChildren(List<Comment> comments) {
        for (Comment comment : comments) {
            List<Comment> replys1 = comment.getReplyComments();
            for (Comment comment1 : replys1) {
                //循环迭代，找出子代，存放在tempReplys中
                recursively(comment1);
            }
            //修改顶级节点的reply集合为迭代处理后的集合
            comment.setReplyComments(temReplys);
            //清除临时存放区
            temReplys = new ArrayList<>();
        }
    }

    /*存放迭代找出的所有子代的集合*/
    private List<Comment> temReplys = new ArrayList<>();

    /*递归迭代*/
    private void recursively(Comment comment) {
        //顶节点添加到临时存放集合
        temReplys.add(comment);
        if (comment.getReplyComments().size()>0){
            List<Comment> replys = comment.getReplyComments();
            for (Comment reply : replys) {
                temReplys.add(reply);
                if (reply.getReplyComments().size()>0){
                    recursively(reply);
                }
            }
        }
    }

}